package sdk.webview.fmc.com.fmcsdk.check.persenter;


import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.GetManagerBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.UploadVideDataBean;
import sdk.webview.fmc.com.fmcsdk.bean.UploadVideoBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.RunListPagerBean;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.CheckDetailsView;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.StartWorkView;
import sdk.webview.fmc.com.fmcsdk.db.DatabaseManager;
import sdk.webview.fmc.com.fmcsdk.db.IMAGE;
import sdk.webview.fmc.com.fmcsdk.db.Record;
import sdk.webview.fmc.com.fmcsdk.util.AESUtil;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.DateUtil;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.HandleJsEvent;
import sdk.webview.fmc.com.fmcsdk.util.ImageCompressor;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.KLog;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;
import top.zibin.luban.OnCompressListener;

/**
 * Created by ydm on 2017/9/14.
 */

public class StartWorkPersenter extends BasePresenter<StartWorkView> {


    public void getRunListPager(String assetId, String type) {
        getApi(UserApi.class).apiRunListPager(getDefaultAddress() + Url.GET_RUN_LIST_PAGE, UserHelper.getToken(), assetId, "1", "50", type)
                .compose(new ResponseTransformer<>(this.<RunListPagerBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<RunListPagerBean>(view) {
                    @Override
                    public void success(RunListPagerBean baseData) {
                        view.getRunListPager(baseData);

                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }


    public void getReportStatus(String assetId, String type, String projId) {
        view.showLoading();
        String time = System.currentTimeMillis() + "";
        getApi(UserApi.class).apiReportStatus(getDefaultAddress() + Url.GET_REPORT_STATUS, UserHelper.getToken(), assetId, type, time, time, projId)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.getReportStatus(type);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();

                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }

    private SharedPreferences defaultSharedPreferences;

    public void uploadImageNew(File file) {
        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(view.getViewContext());
        if (!file.exists()) {
            return;
        }
        new ImageCompressor(view.getViewContext()).compressImageInPlace(file.getPath(), new OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                RequestBody typeBody = RequestBody.create(MediaType.parse("multipart/form-data"), "");
                RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis() + "");//,+""

                ApiFactory.getFactory().create(UserApi.class).uploadImgForClient(defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody, typeBody, timeBody)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<UploadImage>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onNext(UploadImage result) {
                                view.uploadSuccess(null);
                            }
                        });

            }

            @Override
            public void onError(Throwable e) {
            }
        });


    }

    public void updateInspectionPoint(String projid,
                                      Long actUploadDate,
                                      List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList,
                                      String description,
                                      Long finishDate,
                                      String id,
                                      Integer isSkip,
                                      String locationDesc,
                                      String offlineDate,
                                      String orderId,
                                      String status,
                                      String type,
                                      String workOrderId) {
        view.showLoading();
        KLog.e(GsonUtil.BeanToJson(checkList));
        HashMap<String, Object> map = new HashMap<>();
        map.put("actUploadDate", actUploadDate);
        map.put("checkList", checkList);
        map.put("description", description);
        map.put("finishDate", finishDate);
        map.put("id", id);
        map.put("isSkip", isSkip);
        map.put("locationDesc", locationDesc);
        map.put("offlineDate", offlineDate);
        map.put("orderId", orderId);
        map.put("status", status);
        if (!StringUtils.isEmpty(workOrderId)){
            map.put("workOrderId",workOrderId);
        }

        String json = new Gson().toJson(map);
        KLog.e("霍东升检查参数:"+id, json);
        KLog.e("霍东升检查参数123:"+id, GsonUtil.BeanToJson(map));
        RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), new Gson().toJson(map));

        getApi(UserApi.class).updateInspectionPoint(getDefaultAddress() + Url.POST_UPDATE_POINT, UserHelper.getToken(), projid, requestBody)
                .compose(new ResponseTransformer<>(this.bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.updatePointSuccess(type);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        map.put("projid", projid);
                        view.updatePointFail(map);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }

    /**
     * 上传图片到客户端
     */
    public void uploadImgForClient(String url, String locationUrl, String id) {
        File files = new File(url);
        if (!files.exists()) {
            files = new File(url);
            if (!files.exists()) {
                return;
            }
        }
        new ImageCompressor(view.getViewContext()).compressImageInPlace(url, new OnCompressListener() {
            @Override
            public void onStart() {
                view.showLoading();
            }

            @Override
            public void onSuccess(File file) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                RequestBody typeBody = RequestBody.create(MediaType.parse("multipart/form-data"), id);//,System.currentTimeMillis()+""
                RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis() + "");//,+""
                getApi(UserApi.class).uploadImgForClient(getDefaultAddress() + Url.UPLOAD_IMG, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody, typeBody, timeBody)
                        .compose(new ResponseTransformer<>(bindToLifeCycle(1)))
                        .subscribe(new ResponseSubscriber<UploadImage>(view) {
                            @Override
                            public void success(UploadImage baseData) {
                                //图片上传到服务器
                                view.uploadImgForClientSuccess(baseData, locationUrl);
                                //uploadFilesService(baseData,ids,url,ownerId);
                                view.hideLoading();
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                view.uploadImgForClientOnError(url, locationUrl, id);
                                //view.uploadImgForClientOnError(url, ids);
                                view.hideLoading();
                            }


                            @Override
                            public void onRequestAgain() {
                                uploadImgForClient(url, locationUrl, id);
                            }
                        });


            }

            @Override
            public void onError(Throwable e) {
                //view.uploadImgForClientOnError(url, ids);
                view.uploadImgForClientOnError(url, locationUrl, id);
            }
        });


    }

    public void updateInspectionPointWorkRequest(String picId, String url, String shrinkUrl, String ownerId, String locationUrl, String description,boolean isPic) {
        String ownerObject = "insp_order_chklist";
        String ownerType = "chklist";
        String storePath = "/filestorage/" + DateUtil.getCurrentDate("yyyyMMdd") + "/" + picId + ".jpg";
        String thumbImagePath = "/filestorage/" + DateUtil.getCurrentDate("yyyyMMdd") + "/thumb_" + picId + ".jpg";
        String offlineDate = DateUtil.getCurrentDate("yyyy/MM/dd+HH:mm:ss");
        view.showLoading();

        getApi(UserApi.class).updateInspectionPointWorkRequest(getDefaultAddress() + Url.UPLOAD_FILES_SERVICE, Url.XMLHTTPREQUEST,
                        UserHelper.getToken(), UserHelper.getToken(), picId, ownerId, ownerObject, ownerType, storePath, "jpg", thumbImagePath, "IMAGE", offlineDate, description)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.updateInspectionPointWorkRequestSuccess(picId, url, shrinkUrl,isPic);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.updateInspectionPointWorkRequestFail(picId, url, shrinkUrl, locationUrl,isPic);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                        updateInspectionPointWorkRequest(picId, url, shrinkUrl, ownerId, locationUrl, description,isPic);
                    }
                });
    }


    public void deletePic(String id, int groupPosition, int position) {
        view.showLoading();
        getApi(UserApi.class).deletePic(getDefaultAddress() + Url.POST_DELETE_PIC, UserHelper.getToken(), id)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        view.deletePicSuccess(groupPosition, position);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }


    public void getManager(String staffId) {
        view.showLoading();
        getApi(UserApi.class).getManager(getDefaultAddress() + Url.GET_MANAGER, UserHelper.getToken(), UserHelper.getToken(), staffId)
                .compose(new ResponseTransformer<>(this.<GetManagerBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<GetManagerBean>() {
                    @Override
                    public void success(GetManagerBean baseData) {
                        view.getManagerSuccess(baseData.getRecord());
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });

    }


    public void uploadVideo(final String localUrl, final String ids, File files) {
//        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), files);
        RequestBody timeBody = RequestBody.create(MediaType.parse("multipart/form-data"), System.currentTimeMillis()+"");//,+""

        RequestBody typeBody = RequestBody.create(MediaType.parse("multipart/form-data"), ids);
        getApi(UserApi.class).uploadVideo(getDefaultAddress() + Url.UPLOAD_VIDEO, Url.XMLHTTPREQUEST, UserHelper.getToken(), requestBody, typeBody,timeBody)
                .compose(new ResponseTransformer<>(this.<UploadVideoBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UploadVideoBean>(view) {
                    @Override
                    public void success(UploadVideoBean baseData) {
                        view.uploadVideoSuccess(baseData.getRecord().getUrl(), localUrl, baseData.getRecord().getId());
                       // view.uploadImgOrVideoEnd();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.uploadVideoError(localUrl, ids);
                    }


                    @Override
                    public void onRequestAgain() {

                    }
                });
    }

    public UploadVideDataBean getUploadVideoSuccessList(String desc, String url, String localUrl, String id, String ownerId, String ownerObject, String ownerType) {
        UploadVideDataBean bean = new UploadVideDataBean();
        bean.setOwnerId(ownerId);
        bean.setOwnerObject(ownerObject);
        bean.setOwnerType(ownerType);
        bean.setUrl(url);
        bean.setMsg(desc);
        bean.setType(Constant.UPLOAD_VIDEO_NETWORK);
        bean.setLocalUrl(localUrl);
        bean.setId(id);
        bean.setIds(id);
        return bean;
    }

}
